<template>
  <div style="overflow: auto;height: 100vh;">
    <Detail :detailForm="detailForm" @editHandle="editHandle"></Detail>

    <div style="padding: 15px 20px;">
      <div class="left-title">课程表</div>

      <div class="flex-jc-s-b">
        <el-button style="margin-top: 20px" @click="showCategoryDialog()">新增章节</el-button>
        <el-button style="margin-top: 20px" type="primary" @click="saveClassTree()">保存课程表</el-button>
      </div>
      <div>
        <el-table :data="data.tableData" row-key="id">
          <el-table-column label="名称" prop="name"/>
          <el-table-column :formatter="formatTypeName" label="课时类型" prop="typeName"/>
          <el-table-column label="关联课时名称" prop="typeAssoName"/>
          <el-table-column label="课时课件" prop="docName"/>
          <el-table-column label="课时题库" prop="questionName"/>
          <el-table-column label="课时顺序" prop="sort" width="80">
            <template #default="scope">
              <template v-if="scope.row.categoryFlag == 1">
                <div class="flex-column flex-al-center all-move">
                  <el-button v-if="scope.$index!=0" :icon="ArrowUp" circle class="move-btn" plain type="warning"
                             @click="moveUp(scope.row)"></el-button>
                  <el-button v-if="data.tableData.findIndex(item=>item.id==scope.row.id)>=0&&data.tableData.findIndex(item=>item.id==scope.row.id)!=data.tableData.length-1" :icon="ArrowDown" circle class="move-btn" plain type="primary"
                             @click="moveDown(scope.row)"></el-button>
                </div>
              </template>
              <template v-else>
                <div class="flex-column flex-al-center all-move">
                  <el-button :icon="ArrowUp" circle class="move-btn" plain type="warning"
                             @click="moveUp(scope.row)"></el-button>
                  <el-button :icon="ArrowDown" circle class="move-btn" plain type="primary"
                             @click="moveDown(scope.row)"></el-button>
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <template v-if="scope.row.categoryFlag == 1">
                <div class="all-move">
                  <el-button text type="primary" @click="addMoreCourse(scope.row)">批量添加</el-button>
                  <el-button text type="primary" @click="showClassDialog(scope.row)">新增课时</el-button>
                  <el-button text type="primary" @click="showCategoryDialog(scope.row)">新增章节</el-button>
                  <el-button text type="primary" @click="showCategoryDialog(scope.row, true)">修改</el-button>
                  <el-button text type="danger" @click="deleteItem(scope.row)">删除</el-button>
                  <el-button text type="danger" @click="deleteAllItem(scope.row)">删除子项</el-button>
                </div>
              </template>
              <template v-else>
                <div class="all-move">
                  <el-button text type="primary" @click="showClassDialog(scope.row, true)">修改
                  </el-button>
                  <el-button text type="danger" @click="deleteItem(scope.row)">删除</el-button>
                </div>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div style="height: 200px;"></div>
    <form-dialog v-model="categoryDialogVisible" :title="data.categoryDialogTitle" @save="saveCategory()">
      <el-form :rules="categoryRules" ref="categoryFormRef" :model="data.categoryForm" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input maxlength="30" v-model="data.categoryForm.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </form-dialog>
    <AssoDialog v-model="classDialogVisible" :chapterList="data.chapterList" :course="detailForm.data"
                :dataForm="data.classForm" :title="data.classDialogTitle" :type="data.type"
                @save="saveClass" ></AssoDialog>
  </div>
</template>

<script setup>
import Detail from '@/views/common/component/detail'
import {ArrowDown, ArrowUp,} from '@element-plus/icons-vue'
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {useRoute} from 'vue-router/dist/vue-router'
import {getCourseDetail} from "@/api/course";
import AssoDialog from "./component/asso-dialog";
import {getTreeItemById, removeTreeItemById} from "../../../../utils/tree";
import {editCourse} from "../../../../api/course";
import {ElMessage} from "element-plus";
import {listDictItemByCode} from "@/api/config/dic";

const router = useRouter()
const route = useRoute()
const loading = ref(false)

const { proxy } = getCurrentInstance()

const classDialogVisible = ref(false)

const categoryDialogVisible = ref(false)

const data = reactive({
  tableData: [],
  classDialogTitle: '新增课时',
  categoryDialogTitle: '新增章节',
  categoryForm: {categoryFlag: 1},
  classForm: {},
  type: 1,//1 单个添加 2 批量添加
  chapterList: []
})

const detailForm = reactive({
  column:[
    {
      name:'名称',
      code: 'name'
    },
    {
      name:'课程类型',
      code: 'categoryName'
    },
    {
      name:'类目',
      code: 'kindName'
    },
    {
      name:'老师',
      code: 'teacherList',
      formatter: (row)=>{
        let teacherList = row.teacherList
        let rs = ''
        if (teacherList) {
          teacherList.forEach((item)=>{
            rs += item.name + '|'
          })
        }
        if (rs) {
          rs = rs.substring(0, rs.length-1)
        }
        return rs
      }
    },
    {
      name:'年份',
      code: 'examYear'
    },
    {
      name:'状态',
      code: 'publishedFlag',
      formatter: (row)=>{
        return row.publishedFlag == 1? '上架' : '下架'
      }
    },
    {
      name:'说明',
      code: 'descr'
    },
  ],
  data: {},
  hasEdit: true
})
const deleteAllItem = (e) => {
  console.log(e.children)
  e.children=[]
}
const initInfo = () => {
  getCourseDetail(route.query.id || '').then((res) => {
    detailForm.data = res.data
    // let structureJson = detailForm.data.structureJson
    //
    // structureJson = structureJson ? structureJson : []
    data.tableData = detailForm.data.structureJson
  })
  listDictItemByCode({typeCode: 'chapterCatalogCode'}).then(res => {
    data.chapterList = res.rows
  })
}

const formatTypeName = (row) => {
  let typeList = proxy.$Const.classTypeList
  let typeObject = typeList.find(item => item.code == row.type)
  if (typeObject) {
    return typeObject.name
  }
  return ''
}

const editHandle = () => {
  router.push({
    path: '/modules/course/course/save',
    query: { id: route.query.id, type: 'edit' }
  })
}

const categoryRules = ({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})

onMounted(() => {
  initInfo()
})

const showCategoryDialog = (targetItem, isEdit) => {
  categoryDialogVisible.value = true
  if (isEdit){
    Object.assign(data.categoryForm, targetItem)
  }else{
    data.categoryForm = {categoryFlag:1, parent: targetItem}
  }
  data.categoryForm.isEdit = isEdit
}

const saveCategory = () => {
  let categoryItem = data.categoryForm
  let newItem = {}
  Object.assign(newItem, categoryItem)
  if (categoryItem.isEdit) {
    editItemHandle(newItem)
  }else {
    addItemHandle(newItem)
  }
  categoryDialogVisible.value = false
}

const showClassDialog = (targetItem, isEdit) => {
  classDialogVisible.value = true
  if (isEdit) {
    Object.assign(data.classForm, targetItem)
  } else {
    data.type = 1
    data.classForm = {parent: targetItem}
  }
  data.classForm.isEdit = isEdit
}
const addMoreCourse = (targetItem) => {
  data.type = 2
  data.classDialogTitle = '批量添加'
  data.classForm = {parent: targetItem}
  classDialogVisible.value = true
}
const saveClass = (value) => {
  let newItem = {}
  Object.assign(newItem, value)
  if (newItem.isEdit) {
    editItemHandle(newItem)
  } else {
    addItemHandle(newItem)
  }
  classDialogVisible.value = false
}
const uuidToNumber = () => {
  // const uuid = uuidv4()
  return Math.floor(Math.random() * 9007199254740991); // JavaScript 最大安全整数
}
const addItemHandle = (item) => {
  item.id = uuidToNumber()
  let parent = item.parent
  let parentItem = []
  if (parent) {
    if (parent.children == null) {
      parent.children = []
    }
    parentItem = parent.children
    delete item.isEdit
    delete item.parent
    parentItem.push(item)
  }else {
    data.tableData = Boolean(data.tableData) ? data.tableData : []
    delete item.isEdit
    delete item.parent
    data.tableData.push(item)
  }


}

const editItemHandle = (item) => {
  let targetItem = getTreeItemById(data.tableData, item.id)
  Object.assign(targetItem, item)

  delete targetItem.isEdit
  delete targetItem.parent
}

const deleteItem = (item) => {
  proxy.$modal.confirm("确定删除该数据？").then(() => {
    removeTreeItemById(data.tableData, item.id)
  })
}

const saveClassTree = () => {
  let treeList = data.tableData

  let reqItem = {id: detailForm.data.id, structureJson: editParent(treeList)}
  editCourse(reqItem).then((res) => {
    ElMessage.success('操作成功');
  })
}
const editParent = (treeList) => {
  treeList.forEach((item) => {
    if (item.children) {
      item.children.forEach(itemChilder => {
        itemChilder.parentId = item.id
      })
    }
  })
  return treeList
}
// 排序
const moveUp = (e) => {

  if (e.categoryFlag == 1) {
    let index = data.tableData.findIndex((item => item.id == e.id))
    if (index >= 0) {
      const temp = data.tableData[index];
      data.tableData.splice(index, 1);
      data.tableData.splice(index - 1, 0, temp);
    }
  } else {
    data.tableData.forEach((item, index) => {
      if (item.children) {
        let childrenIndex = item.children.findIndex((i => i.id == e.id))

        if (childrenIndex == 0) {
          ElMessage({
            message: '已当前已是第一个了哦~',
            type: 'warning',
          })
        } else if (childrenIndex > 0) {
          let temp = data.tableData[index].children[childrenIndex];
          data.tableData[index].children.splice(childrenIndex, 1);
          data.tableData[index].children.splice(childrenIndex - 1, 0, temp);
        }
      }
    })
  }
}
const moveDown = (e) => {
  if (e.categoryFlag == 1) {
    let index = data.tableData.findIndex((item => item.id == e.id))
    if (index < data.tableData.length - 1) {
      const temp = data.tableData[index];
      data.tableData.splice(index, 1);
      data.tableData.splice(index + 1, 0, temp);
    }
  } else {
    data.tableData.forEach((item, index) => {
      if (item.children) {
        let childrenIndex = item.children.findIndex((i => i.id == e.id))
        if (childrenIndex == item.children.length - 1) {
          ElMessage({
            message: '已当前已是最后一个了哦~',
            type: 'warning',
          })
        } else if (childrenIndex >= 0) {
          let temp = data.tableData[index].children[childrenIndex];
          data.tableData[index].children.splice(childrenIndex, 1);
          data.tableData[index].children.splice(childrenIndex + 1, 0, temp);
        }
      }
    })
  }

}
</script>

<style lang="scss">
.all-move {

  .el-button {
    margin-left: 0 !important;
    padding: 0 8px;
  }
}

.move-btn {

  width: 30px;
  height: 30px !important;
  margin-bottom: 10px;
}
</style>
